<template>
  <div class="history">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>好名好运AI</h1>
          <el-menu mode="horizontal" router class="nav-menu">
            <el-menu-item index="/">首页</el-menu-item>
            <el-menu-item index="/name-generator">取名</el-menu-item>
            <el-menu-item index="/history">历史记录</el-menu-item>
            <el-menu-item index="/favorites">收藏</el-menu-item>
          </el-menu>
        </div>
      </el-header>

      <el-main>
        <h2>历史记录</h2>
        
        <el-alert
          title="数据存储提示"
          type="warning"
          description="历史记录数据存储在浏览器本地缓存中，清除浏览器缓存将导致数据丢失。请及时导出或保存重要的名字内容。"
          show-icon
          :closable="false"
          class="storage-alert"
        />
        
        <div v-if="store.history.length === 0" class="empty-state">
          <el-empty description="暂无历史记录">
            <el-button type="primary" @click="$router.push('/name-generator')">去生成名字</el-button>
          </el-empty>
        </div>

        <div v-else class="history-list">
          <el-row justify="end" class="operation-row">
            <el-button type="success" @click="exportHistoryData" class="export-btn">
              <el-icon><Download /></el-icon> 导出历史记录
            </el-button>
            <el-button type="danger" @click="clearAllHistory" :disabled="store.history.length === 0">
              清空全部历史
            </el-button>
          </el-row>
          
          <el-timeline>
            <el-timeline-item
              v-for="record in store.history"
              :key="record.id"
              :timestamp="formatDate(record.date)"
              placement="top"
            >
              <el-card class="history-card">
                <template #header>
                  <div class="card-header">
                    <span>姓氏：{{ record.input.surname }}</span>
                    <el-button
                      type="danger"
                      link
                      @click="deleteRecord(record.id)"
                    >
                      删除
                    </el-button>
                  </div>
                </template>
                
                <div class="record-details">
                  <p><strong>出生日期：</strong>{{ record.input.birthDate }}</p>
                  <p><strong>出生时辰：</strong>{{ record.input.birthTime || '未知' }}</p>
                  <p><strong>性别：</strong>{{ record.input.genders.join(', ') }}</p>
                  <p v-if="record.input.avoidWords">
                    <strong>忌讳字词：</strong>{{ record.input.avoidWords }}
                  </p>
                  <p v-if="record.input.isMultipleBirth">
                    <strong>多胞胎：</strong>{{ record.input.multipleCount }}胞胎
                  </p>
                </div>

                <div class="generated-names">
                  <h3>生成的名字</h3>
                  <el-row :gutter="20">
                    <el-col
                      v-for="(nameGroup, index) in record.names"
                      :key="index"
                      :xs="24"
                      :sm="12"
                      :md="8"
                      :lg="8"
                    >
                      <el-card class="name-card" shadow="hover">
                        <template #header>
                          <div class="name-header">
                            <div class="full-names">
                              <div v-for="(baby, babyIndex) in nameGroup.fullNames" :key="babyIndex">
                                <span class="baby-name">{{ baby.fullName }}</span>
                                <span class="baby-gender">({{ baby.gender }})</span>
                              </div>
                            </div>
                            <el-button
                              type="primary"
                              link
                              @click="saveName(nameGroup)"
                            >
                              收藏
                            </el-button>
                          </div>
                        </template>
                        <div class="name-details">
                          <p><strong>含义：</strong>{{ nameGroup.meaning }}</p>
                          <p v-if="nameGroup.relationMeaning"><strong>关联含义：</strong>{{ nameGroup.relationMeaning }}</p>
                          <p><strong>五行：</strong>{{ nameGroup.wuxing }}</p>
                          <p><strong>生肖：</strong>{{ nameGroup.zodiac }}</p>
                          <p><strong>音韵：</strong>{{ nameGroup.phonetics }}</p>
                          <p><strong>字形：</strong>{{ nameGroup.structure }}</p>
                        </div>
                      </el-card>
                    </el-col>
                  </el-row>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-main>
      <Footer />
    </el-container>
  </div>
</template>

<script setup>
import { useNameStore } from '../stores/nameStore'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
import { Download } from '@element-plus/icons-vue'
import Footer from '../components/Footer.vue'

const store = useNameStore()
const router = useRouter()

function formatDate(date) {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

async function deleteRecord(id) {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条记录吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    store.deleteHistory(id)
    ElMessage.success('记录已删除')
  } catch {
    // 用户取消删除
  }
}

async function clearAllHistory() {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有历史记录吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 清空历史记录
    store.history.splice(0, store.history.length)
    ElMessage.success('所有历史记录已清空')
  } catch {
    // 用户取消操作
  }
}

function saveName(nameGroup) {
  // 将名字保存到收藏夹
  store.saveToFavorites(nameGroup)
  ElMessage.success('名字已添加到收藏')
}

function exportHistoryData() {
  try {
    const dataStr = store.exportHistory()
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr)
    
    // 创建下载链接
    const exportFileDefaultName = '好名好运AI_历史记录_' + dayjs().format('YYYYMMDD') + '.json'
    
    const linkElement = document.createElement('a')
    linkElement.setAttribute('href', dataUri)
    linkElement.setAttribute('download', exportFileDefaultName)
    linkElement.click()
    
    ElMessage.success('历史记录导出成功')
  } catch (error) {
    console.error('导出历史记录时出错:', error)
    ElMessage.error('导出失败，请重试')
  }
}
</script>

<style scoped>
.history {
  min-height: 100vh;
}

.history-list {
  padding: 20px;
}

.operation-row {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.export-btn {
  margin-right: auto;
}

.history-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-details {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
}

.record-details p {
  margin: 8px 0;
}

.generated-names {
  margin-top: 20px;
}

.name-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.name-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.name-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.full-names {
  flex: 1;
}

.baby-name {
  font-weight: bold;
  margin-right: 5px;
}

.baby-gender {
  color: #606266;
  font-size: 0.9em;
}

.name-details {
  font-size: 14px;
  line-height: 1.6;
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
}

.name-details p {
  margin: 8px 0;
}

.empty-state {
  padding: 40px;
  text-align: center;
}

.el-header {
  background-color: #fff;
  padding: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: auto;
  min-height: 60px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.el-header h1 {
  margin: 0;
  font-size: 24px;
  color: #409EFF;
  white-space: nowrap;
}

.nav-menu {
  border-bottom: none;
  height: 60px;
  background-color: #fff !important;
}

:deep(.el-menu--horizontal) {
  border-bottom: none !important;
}

:deep(.el-menu-item) {
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  color: #2c3e50;
}

:deep(.el-menu-item.is-active) {
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
}

:deep(.el-menu-item:hover) {
  color: #409EFF;
  background-color: transparent;
}

@media (max-width: 768px) {
  .history-list {
    padding: 10px;
  }
  
  .name-card {
    margin-bottom: 15px;
  }
  
  .record-details {
    padding: 10px;
  }
}

.storage-alert {
  margin-bottom: 20px;
}
</style> 